//
//  OAuthViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/3/29.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(App_Key)&redirect_uri=\(Redirect_Uri)"
        guard let url = NSURL(string: urlStr) else {
            return
        }
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    
    }
    
    // MARK: - 内部控制方法
    @IBAction func closeButtonClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func autoFillButtonClick(sender: AnyObject) {
        let idStr = "document.getElementById('userId').value = '1278065207@qq.com';"
        let pwdStr = "document.getElementById('passwd').value = 'Zqasc123163$!';"
        webView.stringByEvaluatingJavaScriptFromString(idStr)
        webView.stringByEvaluatingJavaScriptFromString(pwdStr)
    }
    
}

extension OAuthViewController : UIWebViewDelegate {
    /* 提示加载中 */
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在加载中......")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
    }
    /* 加载完成 */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        /// 获取每次请求到url地址
        guard let urlStr = request.URL?.absoluteString else {
            ZQLog("从服务器请求登录网页失败")
            return false
        }
        /// 判断当前是否是回调授权页面
        /// 回调网址
        let redirect_uri="http://www.imooc.com/"
        if !urlStr.hasPrefix(redirect_uri) {
            ZQLog("不是授权回调页面")
            return true
        }
        /// 判断地址中是否包含error_code=
        let errorKey = "error_code="
        guard urlStr.containsString(errorKey) else { // 授权成功，回调页面不显示
            ZQLog("授权成功")
            let correctKey = "code="
            let code = request.URL?.query?.substringFromIndex(correctKey.endIndex)
            loadAccessToken(code)
            return false
        }
        /// 授权失败，回调页面不显示
        ZQLog("授权失败")
        return false
       
    }
    
    /*
     "access_token" = "2.002zWZwCMjQzhBd958495b6atxA2eD";
     "expires_in" = 157679999;
     "remind_in" = 157679999;
     uid = 2697761443;
     */
    
    /// 换取AccessToken
    private func loadAccessToken(codeStr: String?) {
        guard let code = codeStr else {
            return
        }
        let url = "oauth2/access_token"
        let parameters = ["client_id" : App_Key,
                          "client_secret" : App_Secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : Redirect_Uri]
        NetworkTools.shareInstance.POST(url, parameters: parameters, success: { (task: NSURLSessionDataTask, dict: AnyObject?) -> Void in
            
            let account = UserAccount(dict: dict as! [String : AnyObject])
            account.loadUserInfo({ (account, error) in
                account?.saveAccount()
                
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: false)
                self.closeButtonClick()
                
            })
        }) { (task: NSURLSessionDataTask?, error: NSError) in
                ZQLog(error)
        }
    }
}